package org.example.controller;

import org.example.GetConnection;
import org.example.info.Author;
import org.example.info.Result;
import org.springframework.web.bind.annotation.*;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

//作家的添加查询删除
@RestController
@CrossOrigin(origins = "*")
public class AuthorController {
    private Connection connection = new GetConnection().GetConnection();
    private PreparedStatement statement;
    private ResultSet resultSet;

    @GetMapping("/author")
    public Result<?> getAuthorList() throws SQLException {
        statement = connection.prepareStatement("select * from author");
        resultSet = statement.executeQuery();
        List<Author> authorList = new ArrayList<>();
        while (resultSet.next()) {
            authorList.add(new Author(resultSet.getInt("id"), resultSet.getString("name")));
        }
        return Result.success(authorList);
    }

    @PostMapping("/author")
    public Result<?> addAuthor(@RequestBody Author author) throws SQLException {
        System.out.println(author.toString());
        statement = connection.prepareStatement("insert into author (name,introduce) values (?,?)");
        statement.setString(1, author.getName());
        statement.setString(2, author.getIntroduce());
        statement.executeUpdate();
        return Result.success();
    }

    @PutMapping("/author")
    public Result<?> updateAuthor(@RequestBody Author author) throws SQLException {
        statement = connection.prepareStatement("update author set name = ?,introduce =? where id = ?");
        statement.setString(1, author.getName());
        statement.setString(2, author.getIntroduce());
        statement.setInt(3, author.getId());
        statement.executeUpdate();
        return Result.success();
    }

    @DeleteMapping("/author/{id}")
    public Result<?> deleteAuthor(@PathVariable Integer id) throws SQLException {
        statement = connection.prepareStatement("delete from author where id = ?");
        statement.setInt(1, id);
        statement.executeUpdate();
        return Result.success();
    }
}
